package com.xyht.sca_s.student_manage_system.modules.student_difficulty.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonCodeEnum;
import com.xyht.sca_s.student_manage_system.common.commonReturn.CommonResult;
import com.xyht.sca_s.student_manage_system.common.commonReturn.ResponseResult;
import com.xyht.sca_s.student_manage_system.modules.student_difficulty.entity.SmsStudentDifficultyApply;
import com.xyht.sca_s.student_manage_system.modules.student_difficulty.entity.SmsStudentDifficultyTask;
import com.xyht.sca_s.student_manage_system.modules.student_difficulty.entity.req.SmsStudentDifficultyTaskReq;
import com.xyht.sca_s.student_manage_system.modules.student_difficulty.entity.resp.SmsStudentDifficultyApplyResp;
import com.xyht.sca_s.student_manage_system.modules.student_difficulty.entity.resp.SmsStudentDifficultyTaskResp;
import com.xyht.sca_s.student_manage_system.modules.student_difficulty.mapper.SmsStudentDifficultyApplyMapper;
import com.xyht.sca_s.student_manage_system.modules.student_difficulty.mapper.SmsStudentDifficultyTaskMapper;
import com.xyht.sca_s.student_manage_system.modules.student_difficulty.service.SmsStudentDifficultyTaskService;
import com.xyht.sca_s.student_manage_system.modules.tips.utils.TipsUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

import static com.xyht.sca_s.student_manage_system.common.util.ParamCheckUtil.isNullOrEmpty;
import static com.xyht.sca_s.student_manage_system.modules.student_difficulty.constant.ApplyStatusConstant.APPLY_STATUS_REJECT;
import static com.xyht.sca_s.student_manage_system.modules.student_difficulty.constant.CloseFlagConstant.IS_CLOSE_FALSE;
import static com.xyht.sca_s.student_manage_system.modules.student_difficulty.constant.CloseFlagConstant.IS_CLOSE_TRUE;
import static com.xyht.sca_s.student_manage_system.modules.student_difficulty.constant.TaskRangeFlagConstant.TASK_RANGE_ALL;
import static com.xyht.sca_s.student_manage_system.modules.tips.constant.AppNameConstant.APP_WEB_DIFFICULTY;
import static com.xyht.sca_s.student_manage_system.modules.tips.constant.CommonConstant.TIPS_DIFFICULTY_DESCRIPTION_DEAL;
import static com.xyht.sca_s.student_manage_system.modules.tips.constant.CommonConstant.TIPS_DIFFICULTY_TITLE_DEAL;
import static com.xyht.sca_s.student_manage_system.modules.tips.constant.TipsCloseFlagConstant.TIPS_CLOSE;
import static com.xyht.sca_s.student_manage_system.modules.tips.constant.TipsTypeConstant.TIPS_TYPE_DEAL;
import static com.xyht.sca_s.student_manage_system.modules.tips.constant.UserTypeConstant.USER_TYPE_STUDENT;

/**
 * <p>
 * 家庭经济困难认定任务 服务实现类
 * </p>
 *
 * @author XYHT
 * @since 2023-03-01
 */
@Service
public class SmsStudentDifficultyTaskServiceImpl extends ServiceImpl<SmsStudentDifficultyTaskMapper, SmsStudentDifficultyTask> implements SmsStudentDifficultyTaskService {
    @Autowired
    private SmsStudentDifficultyTaskMapper smsStudentDifficultyTaskMapper;
    @Autowired
    private TipsUtil tipsUtil;
    @Autowired
    private SmsStudentDifficultyApplyMapper smsStudentDifficultyApplyMapper;


    @Override
    public ResponseResult addDifficultyTask(SmsStudentDifficultyTaskReq smsStudentDifficultyTaskReq, String user_id) {
        if (isNullOrEmpty(smsStudentDifficultyTaskReq.getTaskName())
                || isNullOrEmpty(smsStudentDifficultyTaskReq.getTaskRange())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }
        if (smsStudentDifficultyTaskReq.getTaskRange() != TASK_RANGE_ALL) {
            if (smsStudentDifficultyTaskReq.getRangeId() == null || smsStudentDifficultyTaskReq.getRangeId().size() < 1) {
                return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
            }
        }

        SmsStudentDifficultyTask smsStudentDifficultyTask = new SmsStudentDifficultyTask();
        BeanUtils.copyProperties(smsStudentDifficultyTaskReq, smsStudentDifficultyTask);
        smsStudentDifficultyTask.setRangeId(smsStudentDifficultyTaskReq.getRangeId().toString());
        smsStudentDifficultyTask.setUserId(user_id);

        smsStudentDifficultyTaskMapper.insert(smsStudentDifficultyTask);

        //消息待办添加
        tipsUtil.addTips(TIPS_DIFFICULTY_TITLE_DEAL,
                TIPS_DIFFICULTY_DESCRIPTION_DEAL, //TIPS_LEAVE_DESCRIPTION_MESSAGE
                TIPS_TYPE_DEAL,
                APP_WEB_DIFFICULTY,
                smsStudentDifficultyTaskReq.getTaskRange(), //RANGE_TYPE_ROLE
                smsStudentDifficultyTaskReq.getRangeId().toString(),
                smsStudentDifficultyTask.getId(),
                USER_TYPE_STUDENT,
                smsStudentDifficultyTaskReq.getExpirationTime()
        );
        return CommonResult.success();
    }

    @Override
    public ResponseResult closeDifficultyTask(SmsStudentDifficultyTaskReq smsStudentDifficultyTaskReq) {
        if (isNullOrEmpty(smsStudentDifficultyTaskReq.getId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        SmsStudentDifficultyTask task = smsStudentDifficultyTaskMapper.selectById(smsStudentDifficultyTaskReq.getId());
        if (task == null || task.getId() == null) {
            return CommonResult.failed(CommonCodeEnum.DIFFICULTY_NOT_EXIST);
        }

        SmsStudentDifficultyTask smsStudentDifficultyTask = new SmsStudentDifficultyTask();
        smsStudentDifficultyTask.setId(smsStudentDifficultyTaskReq.getId());
        smsStudentDifficultyTask.setIsClose(IS_CLOSE_TRUE);

        smsStudentDifficultyTaskMapper.updateById(smsStudentDifficultyTask);

        //关闭消息待办
        tipsUtil.finishTips(smsStudentDifficultyTaskReq.getId(), null, TIPS_CLOSE);

        return CommonResult.success();
    }

    @Override
    public ResponseResult deleteDifficultyTask(SmsStudentDifficultyTaskReq smsStudentDifficultyTaskReq) {
        if (isNullOrEmpty(smsStudentDifficultyTaskReq.getId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        SmsStudentDifficultyTask task = smsStudentDifficultyTaskMapper.selectById(smsStudentDifficultyTaskReq.getId());
        if (task == null || task.getId() == null) {
            return CommonResult.failed(CommonCodeEnum.DIFFICULTY_NOT_EXIST);
        }

        List<SmsStudentDifficultyApply> applyList = smsStudentDifficultyApplyMapper.selectList(new QueryWrapper<SmsStudentDifficultyApply>()
                .lambda()
                .eq(SmsStudentDifficultyApply::getTaskId, smsStudentDifficultyTaskReq.getId()));
        if (applyList != null && applyList.size() > 0) {
            return CommonResult.failed(CommonCodeEnum.DIFFICULTY_CAN_NOT_DELETE);
        }
        smsStudentDifficultyTaskMapper.deleteById(smsStudentDifficultyTaskReq.getId());

        //关闭消息待办
        tipsUtil.finishTips(smsStudentDifficultyTaskReq.getId(), null, TIPS_CLOSE);

        return CommonResult.success();
    }

    @Override
    public ResponseResult updateDifficultyTask(SmsStudentDifficultyTaskReq smsStudentDifficultyTaskReq) {
        if (isNullOrEmpty(smsStudentDifficultyTaskReq.getId())) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        SmsStudentDifficultyTask DifficultyTask = smsStudentDifficultyTaskMapper.selectById(smsStudentDifficultyTaskReq.getId());
        if (DifficultyTask == null || DifficultyTask.getId() == null) {
            return CommonResult.failed(CommonCodeEnum.DIFFICULTY_NOT_EXIST);
        }

        //超时置位
        List<String> taskIDList = smsStudentDifficultyTaskMapper.selectList(new QueryWrapper<SmsStudentDifficultyTask>()
                .lambda()
                .eq(SmsStudentDifficultyTask::getIsClose, IS_CLOSE_FALSE)
                .lt(SmsStudentDifficultyTask::getExpirationTime, new Date()))
                .stream()
                .map(SmsStudentDifficultyTask::getId)
                .collect(Collectors.toList());
        if (taskIDList.size() > 0) {
            SmsStudentDifficultyTask outTimeTask = new SmsStudentDifficultyTask();
            outTimeTask.setIsClose(IS_CLOSE_TRUE);
            smsStudentDifficultyTaskMapper.update(outTimeTask, new QueryWrapper<SmsStudentDifficultyTask>()
                    .lambda().in(SmsStudentDifficultyTask::getId, taskIDList));
        }

        List<SmsStudentDifficultyTask> closeTask = smsStudentDifficultyTaskMapper.selectList(new QueryWrapper<SmsStudentDifficultyTask>()
                .lambda().eq(SmsStudentDifficultyTask::getId, smsStudentDifficultyTaskReq.getId())
                .eq(SmsStudentDifficultyTask::getIsClose, IS_CLOSE_TRUE));
        if (closeTask != null && closeTask.size() > 0) {
            return CommonResult.failed(CommonCodeEnum.DIFFICULTY_IS_CLOSED);
        }

        SmsStudentDifficultyTask task = new SmsStudentDifficultyTask();
        if (!isNullOrEmpty(smsStudentDifficultyTaskReq.getTaskName())) {
            task.setTaskName(smsStudentDifficultyTaskReq.getTaskName());
        }
        task.setId(smsStudentDifficultyTaskReq.getId());
        smsStudentDifficultyTaskMapper.updateById(task);
        return CommonResult.success();
    }

    @Override
    public ResponseResult getDifficultyTaskList(Integer pageNum, Integer pageSize, Integer is_close, String user_id, String search_str) {
//        if (isNullOrEmpty(is_close)) {
//            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
//        }

        //超时置位
        List<String> taskIDList = smsStudentDifficultyTaskMapper.selectList(new QueryWrapper<SmsStudentDifficultyTask>()
                .lambda()
                .eq(SmsStudentDifficultyTask::getIsClose, IS_CLOSE_FALSE)
                .lt(SmsStudentDifficultyTask::getExpirationTime, new Date()))
                .stream()
                .map(SmsStudentDifficultyTask::getId)
                .collect(Collectors.toList());
        if (taskIDList.size() > 0) {
            SmsStudentDifficultyTask outTimeTask = new SmsStudentDifficultyTask();
            outTimeTask.setIsClose(IS_CLOSE_TRUE);
            smsStudentDifficultyTaskMapper.update(outTimeTask, new QueryWrapper<SmsStudentDifficultyTask>()
                    .lambda().in(SmsStudentDifficultyTask::getId, taskIDList));
        }

        Page<SmsStudentDifficultyTask> page = new Page<>(pageNum, pageSize);
        QueryWrapper<SmsStudentDifficultyTask> queryWrapper = new QueryWrapper<>();
        if (!isNullOrEmpty(search_str)) {
            queryWrapper.lambda().eq(SmsStudentDifficultyTask::getTaskName, search_str);
        }
        if (!isNullOrEmpty(is_close)) {
            queryWrapper.lambda().eq(SmsStudentDifficultyTask::getIsClose, is_close);
        }
        queryWrapper.lambda()
                .eq(SmsStudentDifficultyTask::getUserId, user_id)
                .orderByDesc(SmsStudentDifficultyTask::getCreateTime);
        smsStudentDifficultyTaskMapper.selectPage(page, queryWrapper);
        List<SmsStudentDifficultyTaskResp> resultList = page.getRecords().stream().map(task -> {
            SmsStudentDifficultyTaskResp taskResp = new SmsStudentDifficultyTaskResp();
            BeanUtils.copyProperties(task, taskResp);

            Integer fill_num = smsStudentDifficultyApplyMapper.selectCount(new QueryWrapper<SmsStudentDifficultyApply>()
                    .lambda()
                    .eq(SmsStudentDifficultyApply::getTaskId, task.getId()));
            Integer back_num = smsStudentDifficultyApplyMapper.selectCount(new QueryWrapper<SmsStudentDifficultyApply>()
                    .lambda()
                    .eq(SmsStudentDifficultyApply::getTaskId, task.getId())
                    .eq(SmsStudentDifficultyApply::getApplyStatus, APPLY_STATUS_REJECT));
            taskResp.setBackNum(back_num);
            taskResp.setFillNum(fill_num);
            return taskResp;
        }).collect(Collectors.toList());
        int total = (int) page.getTotal();
        return CommonResult.success(resultList, total);
    }

    @Override
    public ResponseResult getDifficultyTaskDetail(String task_id, String user_id) {
        if (isNullOrEmpty(task_id)) {
            return CommonResult.failed(CommonCodeEnum.INVALID_PARAM);
        }

        SmsStudentDifficultyTask task = smsStudentDifficultyTaskMapper.selectById(task_id);
        if (task == null || task.getId() == null) {
            return CommonResult.failed(CommonCodeEnum.DIFFICULTY_NOT_EXIST);
        }

        SmsStudentDifficultyTaskResp taskResp = new SmsStudentDifficultyTaskResp();
        BeanUtils.copyProperties(task, taskResp);

        Integer fill_num = smsStudentDifficultyApplyMapper.selectCount(new QueryWrapper<SmsStudentDifficultyApply>()
                .lambda()
                .eq(SmsStudentDifficultyApply::getTaskId, task.getId()));
        Integer back_num = smsStudentDifficultyApplyMapper.selectCount(new QueryWrapper<SmsStudentDifficultyApply>()
                .lambda()
                .eq(SmsStudentDifficultyApply::getTaskId, task.getId())
                .eq(SmsStudentDifficultyApply::getApplyStatus, APPLY_STATUS_REJECT));
        taskResp.setBackNum(back_num);
        taskResp.setFillNum(fill_num);

        List<SmsStudentDifficultyApplyResp> applyRespList = smsStudentDifficultyApplyMapper.selectList(new QueryWrapper<SmsStudentDifficultyApply>()
                .lambda()
                .eq(SmsStudentDifficultyApply::getTaskId, taskResp.getId())
                .orderByDesc(SmsStudentDifficultyApply::getCreateTime))
                .stream()
                .map(apply -> {
                    SmsStudentDifficultyApplyResp applyResp = new SmsStudentDifficultyApplyResp();
                    BeanUtils.copyProperties(apply, applyResp);
                    return applyResp;
                })
                .collect(Collectors.toList());
        taskResp.setApplyList(applyRespList);
        return CommonResult.success(taskResp);
    }
}
